package controllers

import (
	"commerce/common"
	"commerce/data"
	"commerce/model"
	"html/template"
	"net/http"
	"path/filepath"
	"strconv"
	"strings"
)

func init() {

	common.Templates["goodsAttr"] = template.Must(template.ParseFiles(filepath.Join(common.CurDir, "views/templates/goods_attr.html")))
	common.Templates["goodsAttr_edit"] = template.Must(template.ParseFiles(filepath.Join(common.CurDir, "views/templates/goodsattr_edit.html")))
}

func ListGoodsAttr(w http.ResponseWriter, r *http.Request) {

	pageNo, err := strconv.Atoi(r.FormValue("pageNo"))
	if err != nil {
		pageNo = 1
	}
	pageSize, err := strconv.Atoi(r.FormValue("pageSize"))
	if err != nil {
		pageSize = common.PAGE_SIZE
	}

	name := strings.TrimSpace(r.FormValue("name"))

	var page, _ = data.PageGoodsAttr(pageNo, pageSize, name)

	if page == nil {
		common.Templates["5xx"].Execute(w, nil)
		return
	}
	// 分页条件查询使用
	var qs = r.URL.RawQuery

	index := strings.Index(r.RequestURI, "&pageNo=")
	var flag bool
	// 这一步操作是点击分页来的
	if index != -1 {
		qs = r.RequestURI[:index]
		flag = true
	} else {
		// 首次点击搜索按钮查询
		flag = false
		qs = "?"
		if len(name) > 0 {
			qs += "name=" + name
		}
	}
	if flag {
		page.Url = qs
	} else {
		page.Url = r.RequestURI + qs
	}

	common.Templates["goodsAttr"].Execute(w, page)
}

func AddGoodsAttrUIHandler(w http.ResponseWriter, r *http.Request) {

	list, _ := data.ListAllCategory()
	g := model.GoodsAttr{Categories: list}

	common.Templates["goodsAttr_edit"].Execute(w, g)
}

func GetGoodsAttrHandler(w http.ResponseWriter, r *http.Request) {

	id, err := strconv.Atoi(r.FormValue("id"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	c, err := data.GetGoodsAttrById(id)
	if err != nil {
		common.Templates["5xx"].Execute(w, err)
		return
	}
	list, _ := data.ListAllCategory()
	c.Categories = list

	common.Templates["goodsAttr_edit"].Execute(w, c)
}

func AddOrEditGoodsAttrHandler(w http.ResponseWriter, r *http.Request) {

	var id = 0
	idVal := r.PostFormValue("id")
	if len(idVal) > 0 {
		id, _ = strconv.Atoi(idVal)
	}
	goodsAttrName := r.PostFormValue("goodsAttrName")
	options := r.PostFormValue("options")
	categoryId, _ := strconv.Atoi(r.PostFormValue("categoryId"))

	g := model.GoodsAttr{Id: id, Name: goodsAttrName, Options: options, CategoryId: categoryId}
	if id <= 0 {
		id, _ = data.AddGoodsAttr(g)
	} else {
		id, _ = data.UpdateGoodsAttr(g)
	}
	//重定向到列表
	http.Redirect(w, r, "/commerce/api/v2/goodsAttr/list", http.StatusFound)
}

func DeleteGoodsAttrHandler(w http.ResponseWriter, r *http.Request) {

	id, err := strconv.Atoi(r.FormValue("id"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	data.DeleteGoodsAttr(id)

	//重定向到列表
	http.Redirect(w, r, "/commerce/api/v2/goodsAttr/list", http.StatusFound)
}
